package com.cat.yygh.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 全局Filter，统一处理会员登录与外部不允许访问的服务
 * </p>
 */
//@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //判断一下是否是登录接口
        if (antPathMatcher.match("/admin/user/**",path)){
            return chain.filter(exchange);
        }else {
            //对于非登录接口，验证：必须登陆之后才能通过
            List<String> list = request.getHeaders().get("X-Token");
            if (list == null){
                //拦截：
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().set(HttpHeaders.LOCATION,"http://localhost:9528");
//                response.setStatusCode(HttpStatus.UNAUTHORIZED);
//                JsonObject jsonObject = new JsonObject();
//                jsonObject.addProperty("success", false);
//                jsonObject.addProperty("code", 28004);
//                jsonObject.addProperty("data", "鉴权失败");
//                byte[] bits = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
//                DataBuffer wrap = response.bufferFactory().wrap(bits);
//                //response.setStatusCode(HttpStatus.UNAUTHORIZED);
//                //指定编码，否则在浏览器中会中文乱码
//                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
//                response.writeWith(Mono.just(wrap));
                return response.setComplete();//结束请求
            }else {//放行
                return chain.filter(exchange);
            }
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
